package com.hengpeng.itfints.controller.member;

import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.persist.entity.AbstractEntity.BoolValue;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.itfinbase.constants.RespCodeConstants;
import com.hengpeng.itfinbase.constants.TransCodeConstants;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.message.userInfo.UserInfoRegisterRequest;
import com.hengpeng.itfinbase.message.userInfo.UserInfoResponse;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.hengpeng.itfinbase.persist.UserInfo.RegisterSource;
import com.hengpeng.itfinbase.persist.UserInfo.UserInfoType;
import com.hengpeng.itfinbase.persist.VerifyCode.VerifyType;
import com.hengpeng.itfints.config.ConfigUtil;
import com.hengpeng.itfints.constants.SystemConfigUtil;
import com.hengpeng.itfints.constants.TSConstants;
import com.hengpeng.itfints.controller.BaseController;
import com.hengpeng.itfints.tools.CommonUtil;
import com.hengpeng.itfints.tools.PatternUtils;
import com.hengpeng.itfints.vo.MemberSession;

@Controller
public class RegisterController extends BaseController
{

	/**
	 * <pre>
	 * 注册
	 * </pre>
	 * @param request
	 * @param username
	 * @param password
	 * @param mobile
	 * @param recommendCode
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/register")
	@ResponseBody
	public ServiceResult<String> register(HttpServletRequest request, String username, String password, String mobile,String email,
			HttpServletResponse resp) throws Exception {
		String isCan = ConfigUtil.getParameter("permissions.regedit");
		if (isCan.equalsIgnoreCase("false")) {
			return validateFailure(ConfigUtil.getParameter("permissions.regedit.disabled.des"));
		}

		if (username == null || password == null) {
			return validateFailure("用户名不能为空");
		}
		if (username.matches("^\\d+$")) {
			return validateFailure("用户名不能为纯数字");
		}
		if (!PatternUtils.USERNAME_PATTERN.matcher(username).matches()) {
			return validateFailure("用户名含有非法字符");
		}
		if (username.toUpperCase().indexOf("HAPPY") != -1) {
			return validateFailure("用户名含有非法字符");
		}
		int uleng = username.getBytes("gbk").length;
		int pleng = password.length();
		if (uleng < 3 || uleng > 16) {
			return validateFailure("用户名字符长度应为3-16之间");
		}
		if (pleng < 6 || pleng > 16) {
			return validateFailure("密码字符长度应为6-16之间");
		}
		if (mobile == null) {
			return validateFailure("手机号码不能为空");
		} else {
			if (!PatternUtils.MOBILE_PATTERN.matcher(mobile).matches()) {
				return validateFailure("手机号码格式不正确");
			}
		}
		UserInfo user = serviceFactory.getUserService().getUserByMobile(mobile);
		if (user != null) {
			return validateFailure("手机号码已经存在");
		}
		user = serviceFactory.getUserService().getUserByEmail(email);
		if (user != null) {
			return validateFailure("邮箱已经存在");
		}

		UserInfoRegisterRequest registerDto = new UserInfoRegisterRequest();
		// registerDto.setVerifyCode(mobilecode);
		registerDto.setMobile(mobile);
		registerDto.setPassword(password);
		registerDto.setUsername(username);
		registerDto.setUserIpAddress(request.getRemoteAddr());
		registerDto.setType(UserInfoType.PERSON);
		registerDto.setRegisterSource(RegisterSource.WEB);
		registerDto.setEmail(email);
		// registerDto.setRecommendCode(recommendCode);
		registerDto.setTransType(TransCodeConstants.MemberTransCode.MEMBER_REGISTER);
		UserInfoResponse response = (UserInfoResponse) serviceFactory.getProtFactory().remoteTrans(registerDto);
		ServiceResult<String> sr = getServiceResult(response, null);
		if (!sr.getIsSuccess()) {
			request.getSession().removeAttribute("vcode");
			return sr;
		}
		/**
		 * 生成激活码
		 */
		String activeCode = CommonUtil.getRandom(6);
		user = serviceFactory.getUserService().getUserByMobile(mobile);
		user.setActiveCode(activeCode);
		serviceFactory.getPersistService().update(user);
		/***
		 * 发送激活邮件
		 */
		StringBuffer url = new StringBuffer();
		String domainName = SystemConfigUtil.getConfigValue("domainName");
		if (!StringUtils.isEmpty(domainName)) {
			if (domainName.indexOf("http://") == -1) {
				url.append("http://");
			}
			url.append(domainName);
		} else {
			url.append(request.getScheme());
			url.append("://");
			url.append(request.getServerName());
			url.append(":");
			url.append(request.getServerPort());
			url.append(request.getContextPath());
		}
		url.append("memberCenter/doValidEmail.htm");
		serviceFactory.getUserService().sendMailForValid(email, username,activeCode,
				url.toString(), "/page/register/active_success.jsp", "/page/register/active_error.jsp");
		MemberSession session = new MemberSession();
		session.setUser(response.getUserInfo());
		request.getSession().setAttribute(TSConstants.CLIENT_SESSION_MEMBER, session);
		return sr;
	}
	/**
	 * 重新发送邮箱激活码
	 * @param map
	 * @param request
	 * @param mobile
	 * @return
	 */
	@RequestMapping(value = "/resendEmailActiveCode")
	@ResponseBody
	public ServiceResult<ResponseMessage>  resendEmailActiveCode(ModelMap map, HttpServletRequest request, String mobile) {
		ServiceResult<ResponseMessage> result = new ServiceResult<ResponseMessage>();
		ResponseMessage response = new ResponseMessage();
		/**
		 * 生成激活码
		 */
		String activeCode = CommonUtil.getRandom(6);
		UserInfo user = serviceFactory.getUserService().getUserByMobile(mobile);
		user.setActiveCode(activeCode);
		serviceFactory.getPersistService().update(user);
		/***
		 * 发送激活邮件
		 */
		StringBuffer url = new StringBuffer();
		String domainName = SystemConfigUtil.getConfigValue("domainName");
		if (!StringUtils.isEmpty(domainName)) {
			if (domainName.indexOf("http://") == -1) {
				url.append("http://");
			}
			url.append(domainName);
		} else {
			url.append(request.getScheme());
			url.append("://");
			url.append(request.getServerName());
			url.append(":");
			url.append(request.getServerPort());
			url.append(request.getContextPath());
		}
		url.append("/memberCenter/doValidEmail.htm");
		serviceFactory.getUserService().sendMailForValid(user.getEmail(), user.getUserName(),activeCode,
				url.toString(),"/page/register/active_success.jsp", "/page/register/active_error.jsp");
		result.setCode(RespCodeConstants.CommonCode.TRANS_SUC);
		result.setMessage(RespCodeConstants.CommonCode.TRANS_SUC_MSG);
		result.setReturnValue(response);
		return result;
	}
	/**
	 * <pre>
	 * 注册第二步：激活
	 * </pre>
	 * @param request
	 * @param username
	 * @param password
	 * @param mobile
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/step_two_register_active")
	public String step_two_register_active(ModelMap map, HttpServletRequest request, String mobile) throws Exception {
		UserInfo user = serviceFactory.getUserService().getUserByMobile(mobile);
		map.put("user", user);
		return "/page/register/step_two_active.jsp";
	}
	/**
	 * 转向激活页面
	 * @param map
	 * @param request
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/toActive")
	public String toActive(ModelMap map, HttpServletRequest request, String userId){
		UserInfo user = serviceFactory.getPersistService().get(UserInfo.class, Long.parseLong(userId));
		map.put("user", user);
		
		/**
		 * 生成激活码
		 */
		String activeCode = CommonUtil.getRandom(6);
		user.setActiveCode(activeCode);
		serviceFactory.getPersistService().update(user);
		/***
		 * 发送激活邮件
		 */
		StringBuffer url = new StringBuffer();
		String domainName = SystemConfigUtil.getConfigValue("domainName");
		if (!StringUtils.isEmpty(domainName)) {
			if (domainName.indexOf("http://") == -1) {
				url.append("http://");
			}
			url.append(domainName);
		} else {
			url.append(request.getScheme());
			url.append("://");
			url.append(request.getServerName());
			url.append(":");
			url.append(request.getServerPort());
			url.append(request.getContextPath());
		}
		url.append("memberCenter/doValidEmail.htm");
		serviceFactory.getUserService().sendMailForValid(user.getEmail(), user.getUserName(),activeCode,
				url.toString(), "/page/register/active_success.jsp", "/page/register/active_error.jsp");
		
		return "/page/register/step_two_active.jsp";
	}
	/**
	 * <pre>
	 * 激活，成功后转让用户类型选择
	 * </pre>
	 * @param map
	 * @param request
	 * @param email_checkcode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/doActive")
	public String doActive(ModelMap map, HttpServletRequest request, String email_checkcode, Long userid) throws Exception {
		UserInfo user = serviceFactory.getPersistService().get(UserInfo.class, userid);
		if (!StringHelper.isEmpty(email_checkcode) && email_checkcode.equals(user.getActiveCode())) {
			user.setIsEmailCheck(BoolValue.YES);
			user = serviceFactory.getPersistService().update(user);
			map.put("user", user);
			return "/page/register/active_success.jsp";
		} else {//验证码不正确
			return "/page/register/active_error.jsp";
		}
	}
	/**
	 * 重新登陆
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/reLogin")
	public String reLogin(ModelMap map, HttpServletRequest request,HttpServletResponse response, String userid, String backurl) {
		
		MemberSession session = getSessionMember(request);
		if (session != null)
		{
			session.setIsLogin(false);
			UserInfo user = serviceFactory.getUserService().getUserByUserName(session.getUser().getUserName());
			map.put("endTime", new Date());
			map.put("loginTime", user.getLastLoginTime());
		}
		request.getSession().removeAttribute(TSConstants.CLIENT_SESSION_MEMBER);
		/**
		 * 添加返回的url
		 */
		Cookie cookie = new Cookie("backurl",backurl);
		response.addCookie(cookie);
		
		return "/page/login/login.jsp";
	}
	
	/**
	 * <pre>
	 * 转向选择用户类型
	 * </pre>
	 * @param map
	 * @param request
	 * @param email_checkcode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/toselectType")
	public String toselectType(ModelMap map, HttpServletRequest request, Long userid) throws Exception {
		UserInfo user = serviceFactory.getPersistService().get(UserInfo.class, userid);
		map.put("user", user);
		return "/page/register/step_three_selecttype.jsp";
	}
	/**
	 * <pre>
	 * 选择类型
	 * </pre>
	 * @param map
	 * @param request
	 * @param typeone
	 * @param typetwo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/selectType")
	public String selectType(ModelMap map, HttpServletRequest request, String typeone, String typetwo, Long userid) throws Exception {
		UserInfo user = serviceFactory.getPersistService().get(UserInfo.class, userid);
		if ("ENTERPRISE".equals(typeone)) {//企业
			map.put("type", "ENTERPRISE");
			map.put("user", user);
			return "/page/register/fill_enterprise.jsp";
		} else if ("PERSON".equals(typeone)) {//个人
			map.put("type", "PERSON");
			map.put("user", user);
			return "/page/register/fill_person.jsp";
		} else {//其他金融类机构
			map.put("financedeptType", typetwo);
			return "/page/register/fill_other.jsp";
		} 
	}
	/**
	 * <pre>
	 * 用户信息保存
	 * </pre>
	 * @param map
	 * @param request
	 * @param user
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/registerSave")
	public String registerSave(ModelMap map, HttpServletRequest request, UserInfo user) throws Exception {
		user.setUpdateTime(new Date());
		user.setRegisterTime(new Date());
		serviceFactory.getPersistService().update(user);
		return "/index.htm";
	}
	
	
	/**
	 * 手机验证发送短信
	 * @return
	 */
	@RequestMapping(value = "/sendRegValidSMS")
	@ResponseBody
	public ServiceResult<Long> sendValidSMS(HttpServletRequest request, String mobile)
	{
		ServiceResult<Long> result = new ServiceResult<Long>();
		if (StringUtils.isEmpty(mobile))
		{
			return validateFailure("参数为空");
		}
		UserInfo user = serviceFactory.getUserService().getUserByMobile(mobile);
		if (user != null)
		{
			return validateFailure("新手机号码已经存在");
		}
		Object sendTime = request.getSession().getAttribute("REGSMSTIME");
		long timeInterval = 30l;
		long nowTime = Calendar.getInstance().getTimeInMillis();
		if (sendTime == null)
		{
			request.getSession().setAttribute("REGSMSTIME", nowTime);
		}
		else
		{
			long countDown = nowTime - Long.parseLong(String.valueOf(sendTime));
			if (countDown >= 1000 * timeInterval)
			{
				request.getSession().setAttribute("REGSMSTIME", nowTime);
			}
			else
			{
				return validateFailure((timeInterval - countDown / 1000) + "s后，才能再次发送短信验证码");
			}
		}

		ResponseMessage response = serviceFactory.getUserService().sendSMSForValidMobile(null, mobile, null,
				VerifyType.REGISTER);
		if (response != null)
		{
			if (RespCodeConstants.CommonCode.TRANS_SUC.equals(response.getRespCode()))
			{
				result.setIsSuccess(true);
				result.setMessage("已发送验证邮件");
				result.setReturnValue(timeInterval);
			}
			else
			{
				return validateFailure(response.getRespDesc());
			}
		}
		else
		{
			return validateFailure("发送验证邮件失败");
		}
		return result;
	}
}
